package com.gimi.cloud.bbp.manage.service.prod.impl;

import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.ReflectUtils;
import com.gimi.cloud.bbp.common.utils.StringUtil;
import com.gimi.cloud.bbp.dao.dao.prod.EcCategoryBrandRelaDao;
import com.gimi.cloud.bbp.dao.dao.prod.EcProdCategoryDao;
import com.gimi.cloud.bbp.dao.dao.product.ProductDao;
import com.gimi.cloud.bbp.dao.myMapper.core.query.QueryParam;
import com.gimi.cloud.bbp.dto.prod.EcProdCatModelDTO;
import com.gimi.cloud.bbp.dto.prod.EcProdCatModelValueDTO;
import com.gimi.cloud.bbp.dto.prod.EcProdCategoryDTO;
import com.gimi.cloud.bbp.entity.prod.EcCategoryBrandRelaEntity;
import com.gimi.cloud.bbp.entity.prod.EcProdCategoryEntity;
import com.gimi.cloud.bbp.manage.service.prod.EcProdCatModelService;
import com.gimi.cloud.bbp.manage.service.prod.EcProdCatModelValueService;
import com.gimi.cloud.bbp.manage.service.prod.EcProdCategoryService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* 品类相关接口实现类
* @author wbj
* @Description
* @create 2017-12-18
* @version 1.0
**/
@Service
public class EcProdCategoryServiceImpl implements EcProdCategoryService {
    private static  final Logger logger = LoggerFactory.getLogger(EcProdCategoryServiceImpl.class);
    private final EcProdCategoryDao ecProdCategoryDao;
    private final ProductDao productDao;
    private final EcProdCatModelService ecProdCatModelService;
    private final EcProdCatModelValueService ecProdCatModelValueService;
    private final EcCategoryBrandRelaDao ecCategoryBrandRelaDao;

    @Autowired
    public EcProdCategoryServiceImpl(EcProdCategoryDao ecProdCategoryDao, ProductDao productDao, EcProdCatModelService ecProdCatModelService, EcProdCatModelValueService ecProdCatModelValueService, EcCategoryBrandRelaDao ecCategoryBrandRelaDao) {
        this.ecProdCategoryDao = ecProdCategoryDao;
        this.productDao = productDao;
        this.ecProdCatModelService = ecProdCatModelService;
        this.ecProdCatModelValueService = ecProdCatModelValueService;
        this.ecCategoryBrandRelaDao = ecCategoryBrandRelaDao;
    }

    @Override
    public List<EcProdCategoryDTO> queryList(EcProdCategoryDTO dto, boolean isPaging) throws Exception {
        if(isPaging){
            PageHelper.startPage(dto.getPageNums(),dto.getPageSizes());
        }
        String sql ="SELECT cate.*,parent.prod_cat_name as parent_cat_name" +
                " FROM ec_prod_category cate" +
                " LEFT JOIN ec_prod_category parent ON parent.is_delete = 0 AND parent.prod_cat_id = cate.parent_cat_id" +
                " WHERE cate.is_delete = 0 AND cate.prod_cat_id = :prodCatId AND cate.prod_cat_name LIKE '%'||:prodCatName||'%' " +
                " AND cate.parent_cat_id =:parentCatId AND cate.cat_grade = :catGrade";
        QueryParam queryParam = new QueryParam();
        queryParam.setSql(sql);
        queryParam.setParamObject(dto);
        return ecProdCategoryDao.selectListDTOBySql(queryParam);
    }

    @Override
    public EcProdCategoryDTO load(EcProdCategoryDTO dto, Object id) throws Exception {
        return ecProdCategoryDao.queryProdCategoryByProdCatId(id);
    }

    @Override
    public EcProdCategoryDTO saveOrUpdate(EcProdCategoryDTO dto) throws Exception {
        EcProdCategoryEntity prodCategoryEntity = null;
        if(StringUtils.isNotBlank(dto.getProdCatId())){
            prodCategoryEntity = ecProdCategoryDao.queryBy("prod_cat_id",dto.getProdCatId());
            if(null == prodCategoryEntity){
                throw new MsgException(ResponseCodeEnum.NO_DATA,"未获取到id为"+dto.getProdCatId()+"的品类，保存失败");
            }
            //判断品类分类级别是否改变
            if(prodCategoryEntity.getCatGrade() != dto.getCatGrade()){
                throw new MsgException(ResponseCodeEnum.PRODCAT_CANNOT_CHANGE,"商品品类分类级别和父类编号不能改变");
            }
            //判断当前品类级别里是否有重名
            List<EcProdCategoryDTO> isExist =  ecProdCategoryDao.getCategoryListByName(dto.getProdCatName(),dto.getCatGrade(),dto.getProdCatId());
            if(isExist!=null && isExist.size()>0){
                throw new MsgException(ResponseCodeEnum.PRODCATNAME_IS_EXIT,"商品品类名称已经存在,更新失败");
            }
        }else{
            prodCategoryEntity = new EcProdCategoryEntity();
            //判断是否已经存在该名称的商品
            List<EcProdCategoryDTO> isExist =  ecProdCategoryDao.getCategoryListByNameForAdd(dto.getProdCatName(),dto.getCatGrade());
            if(isExist!=null && isExist.size()>0){
                throw new MsgException(ResponseCodeEnum.PRODCATNAME_IS_EXIT,"商品品类名称已经存在,添加失败");
            }
        }
        ReflectUtils.copyPropertiesIgnoreNullAndEmptyStr(dto,prodCategoryEntity);
        if(StringUtil.isNotBlank(prodCategoryEntity.getProdCatId())){
            ecProdCategoryDao.baseUpdateByPrimaryKey(prodCategoryEntity);
        }else{
            //自动生成主键
            prodCategoryEntity.setProdCatId(this.createCurrentCategoryId(dto));
            ecProdCategoryDao.baseInsert(prodCategoryEntity);
        }
        ReflectUtils.copyPropertiesIgnoreNullAndEmptyStr(prodCategoryEntity,dto);
        //第三级,生成模版属性及模版值
        if(dto.getCatGrade() == 3){
            //模版属性id
            List<Integer> prodCatModelId = new ArrayList<>();
            //模版属性值id
            List<Integer> prodCatModelValueId = new ArrayList<>();
            if(null != dto.getProdCatModel() && dto.getProdCatModel().size() > 0){
                for(EcProdCatModelDTO catmodel:dto.getProdCatModel()){
                    //如果模版属性名不为空
                    if(StringUtil.isNotBlank(catmodel.getProdPropName())){
                        ReflectUtils.copyPropertiesIgnoreNullAndEmptyStr(dto,catmodel);
                        //设置关联id
                        catmodel.setProdCatId(prodCategoryEntity.getProdCatId());
                        catmodel = ecProdCatModelService.saveOrUpdate(catmodel);
                        prodCatModelId.add(catmodel.getModelId());
                        //如果模版值不为空
                        if(null != catmodel.getProdCatModelValue() && catmodel.getProdCatModelValue().size()> 0){
                            for (EcProdCatModelValueDTO catModelValue:catmodel.getProdCatModelValue()){
                                if(StringUtil.isNotBlank(catModelValue.getModelValue())){
                                    ReflectUtils.copyPropertiesIgnoreNullAndEmptyStr(dto,catModelValue);
                                    catModelValue.setModelId(catmodel.getModelId());
                                    ecProdCatModelValueService.saveOrUpdate(catModelValue);
                                    prodCatModelValueId.add(catModelValue.getCmId());
                                }
                            }
                        }
                    }
                }
            }
            //删除失效的品类模版值
            ecProdCatModelValueService.deleteCatModelValueByCatIdExcludeCmIds(dto,prodCategoryEntity.getProdCatId(),prodCatModelValueId);
            //删除失效的品类模版
            ecProdCatModelService.deleteProdCatModelByCatIdExcludeModelIds(dto,prodCategoryEntity.getProdCatId(),prodCatModelId);

            EcCategoryBrandRelaEntity rela = ecCategoryBrandRelaDao.queryBy("prod_cat_id",prodCategoryEntity.getProdCatId());
            if(null == rela){
                rela = new EcCategoryBrandRelaEntity();
                rela.setProdCatId(prodCategoryEntity.getProdCatId());
                //避免空指针，预先初始化一个值
                rela.setProdBrandId(0);
            }
            if(!dto.getPdId().equals(rela.getProdBrandId())){
                rela.setProdBrandId(dto.getPdId());
                ecCategoryBrandRelaDao.baseUpdateByPrimaryKey(rela);
            }
        }
        //TODO 添加操作日志
        return dto;
    }

    @Override
    public int delete(EcProdCategoryDTO dto, Object id, boolean realDel) throws Exception {
        EcProdCategoryEntity prodCategoryEntity = ecProdCategoryDao.queryBy("prod_cat_id",id);
        if(null == prodCategoryEntity){
            throw new MsgException(ResponseCodeEnum.NO_DATA,"未获取到id为"+dto.getProdCatId()+"的品类，删除失败");
        }
        int productCount = productDao.queryProductCountByProdCatId(prodCategoryEntity.getProdCatId());
        if(productCount > 0){
            throw new MsgException(ResponseCodeEnum.PRODCATEGORY_IS_NOT_EXIT,"该品类下存在商品，不允许删除");
        }
        if(!realDel){
            ReflectUtils.copyPropertiesIgnoreNullAndEmptyStr(dto,prodCategoryEntity);
            prodCategoryEntity.setIsDelete(1);
            return ecProdCategoryDao.baseUpdateByPrimaryKey(prodCategoryEntity);
        }
        return ecProdCategoryDao.deleteByPrimaryKey(id);
    }

    @Override
    public String createCurrentCategoryId(EcProdCategoryDTO dto) {
        //因业务变更，id不允许前端填写，由后台生成
        //先查出库里最大值，然后加1即可.
        //截取的开始长度分别为：1级1，2级3，3级6
        //拼接0的位数
        int length = 0;
        //截取的开始长度
        int subStart = 0;
        if(dto.getCatGrade()==1){
            length = 2;
            subStart = 1;
        }else if(dto.getCatGrade()==2){
            length = 3;
            subStart = 3;
        }else{
            length = 4;
            subStart = 6;
        }
        String maxValue = this.findMaxCatIdByGrade(dto.getParentCatId(),subStart);
        String newStr = "0";
        if(!"0".equals(maxValue)){
            newStr = maxValue.replaceFirst("^0*", "");
        }
        int maxV = new Integer(newStr)+1;
        //新增方法，为不同的级别拼接上相应的0的个数
        String id = String.format("%0"+length+"d", maxV);
        //再将父级id拼接上(1级时不拼，其他拼接)
        if(dto.getCatGrade()>1){
            id = dto.getParentCatId()+id;
        }
        return id;
    }

    @Override
    public String findMaxCatIdByGrade(String parentCatId,int subStart) {
        QueryParam param = new QueryParam();
        String sql = "select ifnull(max(SUBSTRING(prod_cat_id,"+subStart+")),'0') from ec_prod_category where parent_cat_id = '"+parentCatId+"' ";
        param.setSql(sql);
        return ecProdCategoryDao.findMaxCatIdByGrade(param);
    }

    @Override
    public EcProdCategoryDTO loadPordCategoryAndInitModelInfo(EcProdCategoryDTO dto, String prodCatId) throws Exception {
        EcProdCategoryDTO ecPordCategory = this.load(dto,prodCatId);
        if(null == ecPordCategory){
            return null;
        }
        EcProdCatModelDTO prodCatModelDTO= new EcProdCatModelDTO();
        ReflectUtils.copyPropertiesIgnoreNullAndEmptyStr(dto,prodCatModelDTO);
        ecPordCategory.setProdCatModel(ecProdCatModelService.getProdCatModelByCatId(prodCatModelDTO,prodCatId));
        return ecPordCategory;
    }

    @Override
    public List<EcProdCategoryDTO> searchCategoryListByGrade(int i) {
        return ecProdCategoryDao.searchCategoryListByGrade(i);
    }
}
